package com.zlsy.learning.leetcode.linkedlist;

import java.util.Objects;

/**
 * @author zhouliang
 * @date 2020/8/19 20:14 java 实现单向循环链表
 */
public class OnewayCircularLinkList {
  public static void main(String[] args) {
    CircularLinkList circularLinkList = new CircularLinkList();
    circularLinkList.initList();
    Node node = circularLinkList.getNode(1);
    if (Objects.nonNull(node)){
        System.out.println(String.format("%s", node.toString()));
    }
    circularLinkList.add(50);
  }
}

class CircularLinkList {
  /** 首元节点 */
  public Node first;
  /** 头结点 */
  public Node head;
  /** 链表长度 */
  int size;

  /**
   * 初始化循环链表
   *
   * @return true or false
   */
  public boolean initList() {
    size = 0;
    first = new Node(null, null);
    // 定义头结点，指向下个节点为null
    head = new Node(-1, null);
    // 首元节点指向头结点形成循环链表
    first.next = head;
    return true;
  }

  /**
   * 判断链表是否为空
   *
   * @return true or false
   */
  public boolean isEmpty() {
    return size == 0;
  }

  /**
   * 获取第i个位置的节点
   *
   * @param i i个位置
   * @return Node
   */
  public Node getNode(int i) {
    Node renode = head;
    // 排除首元节点和头结点;所以J从-2开始
    for (int j = -2; j < i; j++) {
      if (renode == null) {
        break;
      }
      renode = renode.next;
    }
    return renode;
  }

  /**
   * 在末尾添加元素
   *
   * @param data data
   */
  public void add(int data) {
    Node renode = new Node(data, null);
    getNode(size - 1).next = renode;
    renode.next = first.next;
    size++;
  }
}

class Node {
  public Integer data;
  public Node next;

  public Node(Integer data, Node next) {
    this.data = data;
    this.next = next;
  }

  @Override
  public String toString() {
    return "Node{" + "data=" + data + ", next=" + next + '}';
  }
}
